﻿using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Bmp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.Processing;

namespace YaseiAkira.AJ.Util
{
    public class ImageSaver
    {
        private int _quality;

        private static double _baseSize = Math.Pow(1024, 2);
        private double _3M = _baseSize * 3;
        private double _5M = _baseSize * 5;
        private double _8M = _baseSize * 8;
        private double _10M = _baseSize * 10;


        /// <summary>
        /// 自动压缩构造函数 --徐 2020年3月7日
        /// </summary>
        /// <param name="savePath"></param>
        public ImageSaver()
        {

        }

        public async Task CompressSave(Stream stream, string local, string name)
        {
            var img = await Image.LoadAsync(stream);

            CalculateCompressRate(stream.Length);

            name = name.ToLower();

            if (name.Contains(".png"))
            {
                await img.SaveAsPngAsync(Path.Combine(local, name), new PngEncoder
                {
                    CompressionLevel = PngCompressionLevel.BestCompression
                });

            }
            else if (name.Contains(".jpg") || name.Contains(".jpeg"))
            {
                await img.SaveAsJpegAsync(Path.Combine(local, name),
                    new JpegEncoder { Quality = _quality });
            }
            else
            {
                await img.SaveAsync(Path.Combine(local, name));
            }
        }

        private void CalculateCompressRate(long contentLength)
        {
            // <= 1M
            if (contentLength <= _baseSize)
            {
                _quality = 60;
            }
            else if (_baseSize < contentLength && contentLength <= _3M)
            {
                _quality = 50;
            }
            else if (_3M < contentLength && contentLength <= _5M)
            {
                _quality = 40;
            }
            else if (_5M < contentLength && contentLength <= _8M)
            {
                _quality = 20;
            }
            else if (_8M < contentLength && contentLength <= _10M)
            {
                _quality = 10;
            }
            else
            {
                _quality = 0;
            }
        }

    }
}
